import {
  config
} from '../config.js'

const tips = {
  1: '抱歉，出现了一个错误',
}
// # 解构
class HTTP {
  request({
    url,
    data = {},
    method = 'GET'
  }) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method)
    })
  }
  _request(url, resolve, reject, data = {}, method = 'GET') {
    wx.request({
      url: config.api_base_url + url,
      method: method,
      header:{
        openid: wx.getStorageSync('openid'),
        userid:wx.getStorageSync('user_id'),
      },
      data: data,
      success: (res) => {
        const code = res.statusCode.toString()
        if (code.startsWith('2')) {
          resolve(res.data)
        } else {
          reject()
          const error_code = res.data.error_code
          const success = res.data.success
          const msg = res.data.errorMsg
          this._show_error(error_code, success, msg)
        }
      },
      fail: (err) => {
        reject()
      }
    })
  }
  upload({
    url,
    data = {}
  }) {
    return new Promise((resolve, reject) => {
      this._upload(url, resolve, reject, data)
    })
  }

  _upload(url, resolve, reject, data = {}) {
    wx.uploadFile({
      url: config.api_base_url + url, // 仅为示例，非真实的接口地址
      filePath: data.path,
      name: 'file',
      header: {
        openid: wx.getStorageSync('openid'),
        userid: wx.getStorageSync('user_id'),
      },
      success: (res) => {
        const code = res.statusCode.toString()
        if (code.startsWith('2')) {
          resolve(JSON.parse(res.data))
        } else {
          reject()
          const error_code = res.data.error_code
          const success = res.data.success
          const msg = res.data.errorMsg
          this._show_error(error_code, success, msg)
        }
      },
      fail: (err) => {
        reject()
      }
    });
  }

  _show_error(error_code, success, msg) {
    if (error_code != 1000 || !success) {
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
    }
  }
}
export {
  HTTP
}